package dsn

import (
	"strings"
)

/**
|---------------------------------
| 获取dsn
| user: fcl date: 2022/6/29
|---------------------------------
|
*/
// 配置结构需要实现的方发
type IConfig interface {
	SetDsn(dsn string) IConfig
	GetDsn() string
}

type IDsn interface {
	// 获取dsn
	Get(Driver string, config IConfig) string
}

type DsnImpl struct {
	Driver   string
	Instance IConfig
}

var DsnConfig = DsnImpl{}

func Dsn() IDsn {
	return &DsnConfig
}

func (i *DsnImpl) Get(Driver string, config IConfig) string {
	i.Driver = Driver
	i.Instance = config
	i.hanlde()
	return i.Instance.GetDsn()
}

// 处理在没有dsn的情况
func (i *DsnImpl) hanlde() {
	driver := strings.ToUpper(i.Driver)
	switch driver {
	case "MYSQL":
		var mc *MysqlConfig
		mc = i.Instance.(*MysqlConfig)
		if mc.Dsn != "" {
			// 如果dsn存在则直接返回
			return
		}
		// 不存在在则通过host+port+user...组装dsn
		// todo 暂时不实现
		mc.Dsn = mc.User + ":" + mc.Pass + "@tcp(" + mc.Host + ":" + mc.Port + ")/" + mc.DbName
		if mc.Charset != "" {
			mc.Dsn += "?charset=" + mc.Charset
		}
		return
		// sql.Open("mysql", "root:passwd@tcp(127.0.0.1:3306)/test?charset=utf8")
	default:
		panic("No corresponding drive !")
	}

}
